//
//  WTCacheManager.m
//  WTLiveSDKDemo
//
//  Created by ben on 16/10/1.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTCacheManager.h"

NSString* WTDataCacheDataBaseName = @"WTCacheBaseData";


@implementation WTCacheManager

static WTCacheManager *shareManager;
+ (instancetype)shareManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ shareManager = [[self alloc] init]; });
    return shareManager;
}

- (id)init{
    
    if(self = [super init]){
        NSString* path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *dbPath = [path stringByAppendingPathComponent:WTDataCacheDataBaseName];//缓存数据库
        self.db = [[LevelDB alloc] initWithPath:dbPath andName:WTDataCacheDataBaseName];
        
    }
    return self;
}

- (void)save:(id)data key:(NSString*)key{
    [WTCacheManager shareManager].db.encoder = ^ NSData * (LevelDBKey *key, id value) {
        return [NSJSONSerialization dataWithJSONObject:value options:0 error:nil];
    };
    [[WTCacheManager shareManager].db setObject:data forKey:key];
}

- (id)objectForKey:(NSString*)key{
    [WTCacheManager shareManager].db.decoder = ^ id (LevelDBKey *key, NSData *data) {
        
        return [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    };
    id  cache = [[WTCacheManager shareManager].db objectForKey:key];
    return cache;
}
@end

